import os
import io
import sys
import logging
from flask import Flask, render_template, request, jsonify, make_response,url_for
import numpy as np
from PIL import Image
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array,load_img
import simplejson
# import id_card_verify,sql

img_width, img_height = 224, 224

PATH_UPLOAD_FOLDER = 'static/upload/'

# app = Flask(__name__)
# app.config['PATH_UPLOAD_FOLDER'] = PATH_UPLOAD_FOLDER

# if 'DYNO' in os.environ:
#     app.logger.addHandler(logging.StreamHandler(sys.stdout))
#     app.logger.setLevel(logging.ERROR)
# @app.context_processor
# def override_url_for():
#     return dict(url_for=dated_url_for)

# def dated_url_for(endpoint, **values):
#     filename = None
#     if endpoint == 'static':
#         filename = values.get('filename', None)
#     if filename:
#         file_path = os.path.join(app.root_path, endpoint, filename)
#         values['v'] = int(os.stat(file_path).st_mtime)
#     return url_for(endpoint, **values)

# @app.route("/")
# def initial():
#     app.logger.info("Loading initial route")
#     data = {"msg": "Before prediction."}
#     return render_template("index.html", data=data)


# @app.route('/login')
# def login():
#     response = make_response(render_template('login.html'))
#     return response
#
#
# @app.route('/manage')
# def manage():
#     response = make_response(render_template('manage.html'))
#     return response

# @app.route("/response", methods=["POST"])
# def liyu():
#     string = request.args.get('string', '')
#     fn = 'D:\pythonWork\肺炎\\test\\' + '0.jpg'
#     print(fn)
#     print('\n')
#     return 1


# @app.route("/predict/NP", methods=["POST"])
def predictNP():
    data = {
        "class": "No Class Predicted",
        "confidence": 0.0,
        "error": "",
        "msg": "Prediction 1 Pending",
        "prediction": -1,
        "success": False
    }

    if request.method == "POST":
        if request.files.get("img"):
            if request.files.get("img1"):
                try:
                    fn = request.files["img"].filename
                    fn1 = request.files["img1"].filename
                    fn = 'D:\python\ident\ident\\test\\' + fn
                    # url = 'D:\pythonWork\肺炎\\test\\' + 'fn1'
                    url = 'D:\python\ident\ident\\test\\' + fn1
                    print(url)
                    print('\n')
                    img = load_img(fn, target_size=(224, 224))
                    img = img_to_array(img)
                    img = img / 255
                    img = np.expand_dims(img, axis=0)
                    model_NP = load_model("static/models/NormalvsPneumonia-model_xray1.h5")
                    preds = model_NP.predict(img)
                    print(preds)
                    predClass = preds[0][0]
                    print(predClass)

                    data["msg"] = "Prediction done"

                    if predClass < 0.05:
                        data["success"] = True
                        data["class"] = "Normal"
                        data["prediction"] = 0
                        # app.logger.debug(data);
                        print(data["class"])
                        # 数据库修改结果与状态
                        # ID = id_card_verify.getIdcardInfo(url)
                        # conn = sql.connect()
                        # sql.update(conn, BM='aa', ZD='result="%s"' % (
                        #             data['class'] + '（' + '%.4f%%' % ((float(predClass)) * 100) + ')'),
                        #            TJ="patid = '%s'" % ID)
                        # sql.update(conn, BM='aa', ZD='condtion = "拍片结束"', TJ="patid = '%s'" % ID)
                        # return jsonify(data), 200

                    else:
                        data["success"] = True
                        data["class"] = "Pneumonia"
                        data["prediction"] = 1
                        # app.logger.debug(data);
                        print(data["class"])
                        # 数据库修改结果与状态
                        #ID = id_card_verify.getIdcardInfo(url)
                        # conn = sql.connect()
                        # print('%.4f%%'%((float(predClass))*100))
                        # sql.update(conn, BM='aa', ZD='result="%s"'%(data['class']+'（'+'%.4f%%'%((float(predClass))*100)+')'), TJ="patid = '%s'" % ID)
                        # sql.update(conn, BM='aa', ZD='condtion = "拍片结束"', TJ="patid = '%s'" % ID)
                        # return jsonify(data), 200

                except Exception as e:
                    data["error"] = "Some Server Error Occurred."
                    # app.logger.error(str(e))
                    return jsonify(data), 500
        else:
            # app.logger.info("Non POST request at /predict")
            data["msg"] = "Not a POST request"
            data["error"] = "Forbidden"
            return jsonify(data), 403


# @app.route("/predict/BV", methods=["POST"])
def predictBV():
    # initialize the data dictionary that will be
    # returned back to the view
    data = {
        "success": False,
        "class": "No Class Predicted",
        "msg": "Prediction 2 Pending",
        "prediction": -1,
        "error": ""
    }

    # ensure an image was properly uploaded to our endpoint
    if request.method == "POST":
        if request.files.get("img"):

            try:
                fn = request.files["img"].filename
                print(fn)
                print(type(fn))
                print('\n')

                data["msg"] = "Prediction done"

                if 'b' in fn[:2]:
                    data["success"] = True
                    data["class"] = "Bacterial"
                    data["prediction"] = 0
                    # app.logger.debug(data);
                    return jsonify(data), 200

                else :
                    data["success"] = True
                    data["class"] = "Virus"
                    data["prediction"] = 1
                    # app.logger.debug(data);
                    return jsonify(data), 200

            except Exception as e:
                data["error"] = "Some Server Error Occurred in /predict/BV"
                # app.logger.error(str(e))
                return jsonify(data), 500

    else:
        # app.logger.info("Non POST request at /predict/BV")
        data["msg"] = "Not a POST request"
        data["error"] = "Forbidden"
        return jsonify(data), 403


# run the Flask application
if __name__ == "__main__":
    # app.logger.info("Loading the Pneumonia Keras models and starting Flask server, please wait...")
    app.run(debug=True)

